package com.coffee.core.util;

import cn.hutool.crypto.digest.BCrypt;

public class PasswordUtil {
	private static final String CRYPT_ALGO = "$2a";
	private static final String CRYPT_COST = "$10";
	private static final int SALT_LEN = 22;
	
	/**
	 * 密码加密
	 * @param plainStr
	 * @return
	 */
	public static String getPass(String plainStr) {
    	String salt=StringUtil.getRandomDigit(SALT_LEN);
    	salt = CRYPT_ALGO + CRYPT_COST + "$" + salt;
    	String str=BCrypt.hashpw(plainStr, salt) ;
	
    	return str;
	}
	
	
	/**
	 * 验证密码是否正确
	 * @param plainStr 明文密码
	 * @param dbPass 数据库里保存的密文密码
	 * @return
	 */
	public static boolean checkPass(String plainStr, String dbPass) {
		int CRYPT_LEN = SALT_LEN + CRYPT_ALGO.length() + CRYPT_COST.length() + 1;
		String salt=dbPass.substring(0, CRYPT_LEN);
		String str=BCrypt.hashpw(plainStr, salt) ;
    	
		return dbPass.equals(str);
	}
	
	public static void main(String[] args) {
		String plainStr="17554155343".substring(5, 11);
        plainStr = "123456";
        System.out.println(plainStr);
		String dbPass=getPass(plainStr);
		System.out.println(dbPass);
		System.out.println("dbPass:"+dbPass+", len:"+dbPass.length());
		
		System.out.println(checkPass(plainStr, "$2a$10$745233052488744376763uZgGB6rYcRvihYfPOs6POULfkK70MAC2"));
		
	}
}
